package com.zr.sparesubclass.service.impl;

import com.zr.sparesubclass.mapper.SubClassMapper;
import com.zr.sparesubclass.model.*;
import com.zr.sparesubclass.service.SubClassService;
import com.zr.util.AllRecords;
import com.zr.util.ResultVO;
import com.zr.util.ResultVOBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 86151 on 2018/12/29.
 */
@Service
public class SubClassServiceImpl implements SubClassService{

    @Autowired
    private SubClassMapper subClassMapper;
    @Override
    public ResultVO<AllRecords> queryPage(SubClass subClasss) {
        int count = subClassMapper.queryCount(subClasss);
        List<SubClass> subClasses = subClassMapper.queryPage(subClasss);
        //给数据中的数字赋中文值
        assigment(subClasses);
        AllRecords allRecords = new AllRecords();
        allRecords.setDataList(subClasses);
        allRecords.setPageIndex(subClasss.getPageIndex());
        allRecords.setPageSize(subClasss.getPageSize());
        allRecords.setTotalNumber(count);
        allRecords.resetTotalNumber(count);
//        allRecords.setTotalPage(allRecords.getTotalPage());
        return ResultVOBuilder.success(allRecords);
    }

    @Override
    public void updateStatus(UpdateStatusVo updateStatusVo) {
        subClassMapper.updatestatus(updateStatusVo);
    }

    @Override
    public ResultVO<UpdateSubClassVo> update(UpdateSubClassVo updateSubClassVo) {
        //判断信息是否最新
        if(updateSubClassVo.getVersion()==subClassMapper.queryVersion(updateSubClassVo.getId())){
            //判断名称是否重复
           Integer id= subClassMapper.queryName(updateSubClassVo.getName());
            if(id==null){
                //更新
                subClassMapper.updateSubClass(updateSubClassVo);
                return ResultVOBuilder.success(updateSubClassVo);
            }else{
                if(id==updateSubClassVo.getId()){
                    subClassMapper.updateSubClass(updateSubClassVo);
                    return ResultVOBuilder.success(updateSubClassVo);
                }
                return ResultVOBuilder.error("500","名称已存在");
            }
        }else{
            return ResultVOBuilder.error("500","信息不是最新数据，刷新重试");
        }
    }

    @Override
    public void add(AddSubClassVo addSubClassVo) {

    }

    public void assigment(List<SubClass> subClassesList){
        for (SubClass subClass:subClassesList){
            if (subClass.getStatus()){
                subClass.setStatusName(StatusNameEnum.QIYONG.getStatus());
            }else{
                subClass.setStatusName(StatusNameEnum.JINYONG.getStatus());
            }

        }
    }
}
